// const re = require('../../utils/request.js')
let tokenKey = "token" // 将登陆凭证储存以key为“token”储存在本地
let serverUrl = "http://localhost:8080/api"
// serverUrl = "http://rainbrook.w1.luyouxia.net:80/api"
serverUrl = "http://192.168.43.134:8080/api"


//请求头处理函数
function CreateHeader(type) {
  let header = {}
  if (type == 'POST_PARAMS') {
    header = {
      'content-type': 'application/x-www-form-urlencoded'
    }
  } else {
    header = {
      'content-type': 'application/json'
    }
  }
  // 添加 JWT token
  let token = wx.getStorageSync('token')
  header['Authorization'] = token
  return header
}

/**
 * 请求拦截器:
 * 在这里实现的作用是将所有请求前判断用户是否授权获取用户信息
 */
function requestInterceptor(config) {
  // console.log("经过了请求拦截器")
  return new Promise((resolve, reject) => {
    resolve(config)
  })
}

// 响应拦截器
function responseInterceptor(response) {
  // console.log("经过响应拦截器")
  if (response.statusCode === 401) {
    wx.clearStorageSync()
    wx.redirectTo({
      url: '/pages/index/index',
    })
    return
  }
  return new Promise((resolve, reject) => {
    // 处理响应结果
    resolve(response)
  })
}

function baseRequest(method, url, data, times) {
  let header = CreateHeader(url, method)
  return new Promise((resolve, reject) => {
    const config = {
      url: serverUrl + url,
      data: data,
      header: header,
      method: method,
      success: (res => {
        responseInterceptor(res)
          .then(res => {
            resolve(res.data)
          }).catch(res => {
            // 重
            if (times > 0) {
              getRequest(url, data, times - 1).then(res => {
                resolve(res)
              })
            } else {
              wx.showToast({
                title: '请稍后再试',
                icon: "loading",
              })
            }
          })
      }),
      fail: (res => {
        reject(res)
      })
    }
    // 请求拦截器
    requestInterceptor(config)
      .then(config => {
        wx.request(config)
      }).catch(error => {
        reject(error)
      })
  })
}


//get 请求
function getRequest(url, data, times) {
  return baseRequest('GET', url, data, times)
}

// post 请求
function postRequest(url, data, times) {
  return baseRequest('POST', url, data, times)
}

// 上传图片文件（tempFile 是 wx.chooseMedia 获取的数据类型）
function uploadImg(tempFile) {
  const filePath = tempFile.tempFilePath
  if (filePath) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        filePath: filePath,
        name: 'file',
        url: serverUrl + '/img/upload',
        success(res) {
          resolve(JSON.parse(res.data))
        },
        fail: (res) => {
          reject(res)
        }
      })
    })


  }
}

//导出
module.exports = {
  serverUrl: serverUrl,
  getRequest: getRequest,
  postRequest: postRequest,
  uploadImg: uploadImg
}
